
var http = require("http");
var url = require("url");
var util = require("util");

var npm_repo = require("./npm_repo.js");
var eventproxy = require(npm_repo("eventproxy"));

var httpclient = require("./httpclient.js");
var config = require("./config.js");
var app = require("./app.js");

var db = require("./db.js");
var users = require("./users.js");
var weibo = require("./weibo.js");

var serialize = function(name, val, opt){
	let pairs = [name + "=" + val];
	opt = opt || {};

	if (opt.maxAge) pairs.push("Max-Age=" + opt.maxAge);
	if (opt.domain) pairs.push("Domain=" + opt.domain);
	if (opt.path) pairs.push("Path=" + opt.path);
	if (opt.expires) pairs.push("Expires=" + opt.expires.toUTCString());
	if (opt.httpOnly) pairs.push("HttpOnly");
	if (opt.secure) pairs.push("Secure");
	
	return pairs.join(";");
};

var build_callback_page = function(message){
	let page = [];
	page.push("<!DOCTYPE html><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><title>weibo_callback</title></head><body><script type=\"text/javascript\">window.parent.postMessage(JSON.stringify(");
	page.push(JSON.stringify(message));
	page.push("), \"*\");</script></body></html>");
	
	return page.join("");
};

var handle_error = function(res, message){
	let u = ["https://api.weibo.com/oauth2/authorize?client_id="+ config.client_id,
			 "redirect_uri="+ config.redirect_uri,
			 "scope="+ config.scope,
			 "state=weibo",
			 "forelogin=true",
			 "display=mobile"
			].join("&");

	res.statusCode = 200;
	res.setHeader("Content-Type", "application/json; charset=utf-8");
	res.end(JSON.stringify({
		error: message,
		auth_url: u
	}));
}

app.get("/api/initialize", function(req, res){
	let ep = eventproxy.create("user", "weibos", function(user, weibos){
		res.statusCode = 200;
		res.setHeader("Content-Type", "application/json; charset=utf-8");
		res.end(JSON.stringify({
			"user": user,
			"weibos": weibos
		}));
	});

	let uid = req.query.uid || req.cookies.uid;

	let user = users.get(uid);
	if (user)
	{
		//console.log("/api/initialize: user: %s", util.inspect(user));
		ep.emit("user", {
			uid: user.uid,
			name: user.name,
			icon: user.icon
		});
	}
	else
	{
		handle_error(res, "no_valid_user_token");
		return;
	}

	weibo.load(uid).then(function(weibos){
		ep.emit("weibos", weibos);
	}, function(err){
		handle_error(res, err);
		return;
	});
});

app.get("/api/refresh", function(req, res){
	let uid = req.query.uid;
	let min_weibo_id = req.query.min_weibo_id;

	weibo.refresh(uid, min_weibo_id).then(function(weibos){
		res.statusCode = 200;
		res.setHeader("Content-Type", "application/json; charset=utf-8");
		res.end(JSON.stringify({
			"weibos": weibos
		}));
	}, function(err){
		handle_error(res, err);
	});
});

app.get("/api/loadmore", function(req, res){
	let uid = req.query.uid;
	let max_weibo_id = req.query.max_weibo_id;
	
	weibo.loadmore(uid, max_weibo_id).then(function(weibos){
		res.statusCode = 200;
		res.setHeader("Content-Type", "application/json; charset=utf-8");
		res.end(JSON.stringify({
			"weibos": weibos
		}));
	}, function(err){
		handle_error(res, err);
	});
});

/* 处理OAuth2认证OK
 * 回调参数
 * code   string 	用于调用access_token，接口获取授权后的access token
 * state  string 	如果传递参数，会回传该参数。 
 */
app.get("/api/weibo_callback", function(req, res){
	let referer = req.headers["Referer"] || req.headers["Referer"];
	//console.log("/api/weibo_callback referer: " + referer);
	/* TODO: 确认调用来源是weibo API */

	let query = req.query;

	let data = ["client_id="+ config.client_id,
				"client_secret="+ config.client_secret,
				"grant_type=authorization_code",
				"code="+ query.code,
				"redirect_uri="+ config.redirect_uri
			   ].join("&");
	httpclient.post("https://api.weibo.com/oauth2/access_token", data, function(resp) {
		//console.log("OAuth2/access_token, response: %s", resp);

		let token_result = JSON.parse(resp);
		let message = {};

		if (token_result.access_token)
		{
			/* 授权OK时
			 * {
			 *     "access_token": "ACCESS_TOKEN",	// token串
			 * 	   "expires_in": 1234,				// 生命周期，单位为
			 * 	   "remind_in":"798114",			// deprecated
			 * 	   "uid":"12341234"					// 当前授权用户的UID
			 * 	}
			 */

			users.save({
				uid: token_result.uid,
				token: token_result.access_token,
				expire: (new Date()).getTime() + token_result.expires_in * 1000
			});
			message.uid = token_result.uid;
		}
		else
		{
			/* 未成功授权时
			 * {
			 *		"error": "unsupported_response_type",
			 *		"error_code": 21329,
			 *		"error_description": "不支持的ResponseType."
			 * }
			 */
			message.error = token_result.error;
		}

		res.statusCode = 200;
		res.setHeader("Content-Type", "text/html;charset=utf-8");
		res.setHeader("Set-Cookie", serialize("uid", token_result.uid, {
			maxAge: token_result.expires_in
		}));
		res.end(build_callback_page(message));
	});
});

/* 用户取消授权
 * 回调参数
 * source: 应用appkey
 * uid: 取消授权的用户ID
 * auth_end: 取消授权的时间
 */
app.get("/api/weibo_cancel", function(req, res){
	let referer = req.headers["Referer"] || req.headers["referer"];
	console.log("/api/weibo_cancel referer: " + referer);
	/* TODO: 确认调用来源是weibo API */

	users.clear(req.query.uid);

	/*
	res.statusCode = 302;
	res.setHeader("Location", "/");
	res.setHeader("Set-Cookie", serialize("uid", "", {
			expires: new Date(0)
		}));
	res.end();
	*/
});

db.init(config.db).then(function(){
users.init().then(function(){

let httpd = http.createServer();
httpd.on("request", function(req, res) {
	app.run(req, res);
});
httpd.listen(8080, "0.0.0.0");

});
});